package com.haiheng.module_main.dialog
import android.app.Dialog
import android.content.Context
import android.os.Vibrator
import android.view.LayoutInflater
import android.view.View
import android.view.Window
import android.view.WindowManager
import android.widget.Toast
import com.haiheng.library_base.toast.ToastUtils
import com.haiheng.module_main.R
import com.haiheng.module_main.databinding.ActivityScanBinding
import com.haiheng.module_main.databinding.DialogScanBinding
import com.haiheng.module_main.zing.qrcode.BarcodeType
import com.haiheng.module_main.zing.qrcode.QRCodeView


/**
 *
 * @Des:
 * @Author: hwz
 * @Date:2024/8/20 0020
 * @Version: 1.0
 */


class ScanDialog(context: Context, private val callback: OnScanResultCallback)
    : Dialog(context, R.style.FullDialog), QRCodeView.Delegate {

    // 定义自定义的回调接口
    interface OnScanResultCallback {
        fun onScanSuccess(result: String?)
        fun onScanError(error: String?)
    }

    private lateinit var binding: DialogScanBinding
    private val qrCodeView: QRCodeView
    init {
        requestWindowFeature(Window.FEATURE_NO_TITLE)
        setCancelable(true)
        setCanceledOnTouchOutside(true)

        val inflater = LayoutInflater.from(context)
        binding = DialogScanBinding.inflate(inflater)
        window?.decorView?.systemUiVisibility = (View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                or View.SYSTEM_UI_FLAG_FULLSCREEN
                or View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY)
        window?.apply {
            decorView.setPadding(0, 0, 0, 0)
            setLayout(
                WindowManager.LayoutParams.MATCH_PARENT,
                WindowManager.LayoutParams.MATCH_PARENT
            )
        }
        setContentView(binding.root)

        qrCodeView = binding.zxingview
        qrCodeView.setDelegate(this)

        // 初始化扫码视图
        binding.includeTile.tvTitle.setText("扫一扫")
        binding.includeTile.tvClear.visibility = View.GONE
        binding.includeTile.tvCarName.visibility = View.GONE
        binding.includeTile.sflBack.setOnClickListener { dismiss() }
        qrCodeView.setType(BarcodeType.ONE_DIMENSION, null)
    }

    override fun onStart() {
        super.onStart()
        vibrate()
        qrCodeView.startCamera()
        qrCodeView.startSpotAndShowRect()
    }

    override fun onStop() {
        qrCodeView.stopCamera()
        super.onStop()
    }

    private fun vibrate() {
        val vibrator = context.getSystemService(Context.VIBRATOR_SERVICE) as Vibrator
        vibrator.vibrate(200)
    }


    override fun onScanQRCodeSuccess(result: String?) {
        callback.onScanSuccess(result)
        dismiss()
    }

    override fun onCameraAmbientBrightnessChanged(isDark: Boolean) {

    }

    override fun onScanQRCodeOpenCameraError() {
        callback.onScanError("打开相机出错")
        ToastUtils.showShort("打开相机出错")
    }


}